import 'dart:async';
import 'dart:typed_data';

import 'package:blue_plugin/bean/characteristic_info.dart';


class Device {
  late final String _id; //设备Id
  late DeviceState _state;
  late int _mtu;
  late int _rssi;
  late bool _isWatchingRssi;
  late StreamController<DeviceState> _stateStreamController;
  late Stream<DeviceState> _stateStream;
  late StreamController<BleService> _serviceDiscoveryStreamController;
  late Stream<BleService> _serviceDiscoveryStream;
  late StreamController<DeviceSignalResult> _deviceSignalResultStreamController;
  late Stream<DeviceSignalResult> _deviceSignalResultStream;
  late StreamController<int> _rssiStreamController;
  late Stream<int> _rssiStream;
  late Function(bool isSuccess, int newMtu) _androidRequestMtuCallback;

  Device._(this._id, this._rssi) {
    _state = DeviceState.disconnected;
    _mtu = 23;
    _isWatchingRssi = false;
    _stateStreamController = StreamController<DeviceState>();
    _stateStream = _stateStreamController.stream.asBroadcastStream();
    _serviceDiscoveryStreamController = StreamController<BleService>();
    _serviceDiscoveryStream =
        _serviceDiscoveryStreamController.stream.asBroadcastStream();
    _deviceSignalResultStreamController =
        StreamController<DeviceSignalResult>();
    _deviceSignalResultStream =
        _deviceSignalResultStreamController.stream.asBroadcastStream();
    _rssiStreamController = StreamController<int>();
    _rssiStream = _rssiStreamController.stream.asBroadcastStream();
  }

  set stateStreamController(StreamController<DeviceState> value) {
    _stateStreamController = value;
  }

  ///销毁设备对象,不然可能会存在重复的设备对象,当
  void destroy() {
    if (_state != DeviceState.destroyed) {
      _state = DeviceState.destroyed; //将设备状态置为已销毁
      _isWatchingRssi = false;
      _stateStreamController.add(DeviceState.destroyed); //广播状态变化
      // FlutterBlueElves.instance._deviceCache.remove(_id); //从cache中移除
      // FlutterBlueElves.instance._channel
      //     .invokeMethod('destroy', {"id": _id}); //销毁底层的设备对象
      _stateStreamController.close(); //关闭流
      _serviceDiscoveryStreamController.close(); //关闭流
      _deviceSignalResultStreamController.close(); //关闭流
      _rssiStreamController.close(); //关闭流
    }
  }

  ///获取当前设备连接状态
  DeviceState get state => _state;

  set id(String value) {
    _id = value;
  }

  /// 连接设备
  void connect({connectTimeout = 0}) {
    if (_state != DeviceState.destroyed &&
        (_state == DeviceState.disconnected ||
            _state == DeviceState.initiativeDisConnected)) {
      //未连接才能去连接
      _state = DeviceState.connecting; //将设备状态置为连接中
      _stateStreamController.add(DeviceState.connecting); //广播状态变化
      // FlutterBlueElves.instance._channel.invokeMethod('reConnect', {
      //   "id": _id,
      //   "timeout": Platform.isAndroid ? connectTimeout : connectTimeout ~/ 1000
      // }); //重连该设备
    }
  }

  /// 与设备断开连接
  void disConnect() {
    if (_state != DeviceState.destroyed && _state == DeviceState.connected) {
      //已连接才能去断开连接
      _state = DeviceState.disConnecting; //将设备状态置为断开连接中
      _stateStreamController.add(DeviceState.disConnecting); //广播状态变化
      // FlutterBlueElves.instance._channel
      //     .invokeMethod('disConnect', {"id": _id}); //去与该设备断开连接
    }
  }

  ///获取设备状态变化流
  Stream<DeviceState> get stateStream => _stateStream;

  ///发现设备服务
  void discoveryService() {
    if (_state != DeviceState.destroyed && _state == DeviceState.connected) {
      //已连接才能去发现服务
      // FlutterBlueElves.instance._channel
      //     .invokeMethod('discoverService', {"id": _id}); //去发现服务
    }
  }

  ///获取设备蓝牙服务发现流
  Stream<BleService> get serviceDiscoveryStream => _serviceDiscoveryStream;

  ///设置对应的notify特征值的通知
  ///返回true代表设置成功,false代表设置失败
  // Future<bool> setNotify(
  //     String serviceUuid, String characteristicUuid, bool isEnable) async {
  //   bool result = false;
  //   if (_state != DeviceState.destroyed && _state == DeviceState.connected) {
  //     //已连接才能去设置notify的通知
  //     await FlutterBlueElves.instance._channel.invokeMethod('setNotify', {
  //       "id": _id,
  //       "serviceUuid": serviceUuid,
  //       "characteristicUuid": characteristicUuid,
  //       "isEnable": isEnable
  //     }).then((value) => result = value); //去设置notify
  //   }
  //   return result;
  // }

  ///使用设备的read特征值去向设备读取数据
  void readData(String serviceUuid, String characteristicUuid) {
    if (_state != DeviceState.destroyed && _state == DeviceState.connected) {
      //已连接才能去向设备写入数据
      // FlutterBlueElves.instance._channel.invokeMethod('readData', {
      //   "id": _id,
      //   "serviceUuid": serviceUuid,
      //   "characteristicUuid": characteristicUuid
      // }); //去向设备读取数据
    }else{
    }
  }

  ///使用设备的write特征值去向设备发送数据
  void writeData(String serviceUuid, String characteristicUuid,
      bool isNoResponse, Uint8List data) {
    if (_state != DeviceState.destroyed && _state == DeviceState.connected) {
      //已连接才能去向设备写入数据
      // FlutterBlueElves.instance._channel.invokeMethod('writeData', {
      //   "id": _id,
      //   "serviceUuid": serviceUuid,
      //   "characteristicUuid": characteristicUuid,
      //   "isNoResponse": isNoResponse,
      //   "data": data
      // }); //去向设备发送数据
    }
  }

  ///使用设备特征值的描述去向设备读取数据
  void readDescriptorData(
      String serviceUuid, String characteristicUuid, String descriptorUuid) {
    if (_state != DeviceState.destroyed && _state == DeviceState.connected) {
      //已连接才能去向设备写入数据
      // FlutterBlueElves.instance._channel.invokeMethod('readDescriptorData', {
      //   "id": _id,
      //   "serviceUuid": serviceUuid,
      //   "characteristicUuid": characteristicUuid,
      //   "descriptorUuid": descriptorUuid
      // }); //去向设备读取数据
    }
  }

  ///使用设备特征值描述去向设备发送数据
  void writeDescriptorData(String serviceUuid, String characteristicUuid,
      String descriptorUuid, Uint8List data) {
    if (_state != DeviceState.destroyed && _state == DeviceState.connected) {
      //已连接才能去向设备写入数据
      // FlutterBlueElves.instance._channel.invokeMethod('writeDescriptorData', {
      //   "id": _id,
      //   "serviceUuid": serviceUuid,
      //   "characteristicUuid": characteristicUuid,
      //   "descriptorUuid": descriptorUuid,
      //   "data": data
      // }); //去向设备发送数据
    }
  }

  ///获取设备返回数据的结果广播流
  Stream<DeviceSignalResult> get deviceSignalResultStream =>
      _deviceSignalResultStream;

  ///修改设备的mtu,只有android 21 以上才能用
  // void androidRequestMtu(
  //     int newMtu, Function(bool isSuccess, int newMtu) callback) {
  //   _androidRequestMtuCallback = callback;
  //   if (_state != DeviceState.destroyed && _state == DeviceState.connected) {
  //     //已连接才能去向设备写入数据
  //     if (newMtu < 23)
  //       newMtu = 23;
  //     else if (newMtu > 517) newMtu = 517;
  //     FlutterBlueElves.instance._channel.invokeMethod(
  //         'requestMtu', {"id": _id, "newMtu": newMtu}).then((isSended) {
  //       if (!isSended) {
  //         //如果发送请求失败
  //         _androidRequestMtuCallback(false, _mtu);
  //       }
  //     }); //去修改设备mtu
  //   }
  // }

  ///获取当前设备的mtu,默认是23
  int get mtu => _mtu;

  ///获取当前设备的rssi
  int get rssi => _rssi;

  /// 获取当前是否正在监听rssi的变化
  bool get isWatchingRssi => _isWatchingRssi;

  ///获取设备rssi监听流
  Stream<int> get rssiStream => _rssiStream;

  set state(DeviceState value) {
    _state = value;
  }


  set rssiStream(Stream<int> value) {
    _rssiStream = value;
  }


  set isWatchingRssi(bool value) {
    _isWatchingRssi = value;
  }

  set rssi(int value) {
    _rssi = value;
  }

  set mtu(int value) {
    _mtu = value;
  }

  set stateStream(Stream<DeviceState> value) {
    _stateStream = value;
  }

  set rssiStreamController(StreamController<int> value) {
    _rssiStreamController = value;
  }

  set deviceSignalResultStream(Stream<DeviceSignalResult> value) {
    _deviceSignalResultStream = value;
  }

  set deviceSignalResultStreamController(
      StreamController<DeviceSignalResult> value) {
    _deviceSignalResultStreamController = value;
  }

  set serviceDiscoveryStream(Stream<BleService> value) {
    _serviceDiscoveryStream = value;
  }

  set serviceDiscoveryStreamController(StreamController<BleService> value) {
    _serviceDiscoveryStreamController = value;
  }

  ///开始监听设备rssi
  // Future<bool> startWatchRssi() {
  //   return FlutterBlueElves.instance._channel
  //       .invokeMethod('watchRssi', {"id": _id, "isStart": true}).then((ok) {
  //     if (ok) _isWatchingRssi = true;
  //     return ok;
  //   });
  // }

  // ///停止监听设备rssi
  // Future<bool> stopWatchRssi() {
  //   return FlutterBlueElves.instance._channel
  //       .invokeMethod('watchRssi', {"id": _id, "isStart": false}).then((ok) {
  //     if (ok) _isWatchingRssi = false;
  //     return ok;
  //   });
  // }
}



///标示蓝牙设备当前状态
enum DeviceState {
  ///未连接
  disconnected,

  ///正在断开连接
  disConnecting,

  ///连接中
  connecting,

  ///已连接
  connected,

  ///连接超时
  connectTimeout,

  ///主动去断开连接
  initiativeDisConnected,

  ///已销毁
  destroyed
}

///返回发现的蓝牙服务特征值
class BleCharacteristic {
  ///特征值UUID
  final String _uuid;

  ///特征值的配置属性
  final List<CharacteristicInfo> _properties;

  ///特征值的描述对象
  final List<BleDescriptor> _descriptors;

  BleCharacteristic(this._uuid, this._properties, this._descriptors);

  List<CharacteristicInfo> get properties => _properties;

  String get uuid => _uuid;

  List<BleDescriptor> get descriptors => _descriptors;
}

///返回发现的蓝牙服务特征描述对象
class BleDescriptor {
  ///特征值描述对象的UUID
  final String _uuid;

  BleDescriptor(this._uuid);

  String get uuid => _uuid;
}

///设备返回数据的结果
class DeviceSignalResult {
  ///信号类型
  final DeviceSignalType _type;

  ///UUID,要么是特征值uuid,要么是描述uuid
  final String _uuid;

  ///是否成功
  final bool _isSuccess;

  ///返回的数据
  final Uint8List? _data;

  DeviceSignalResult(this._type, this._uuid, this._isSuccess, this._data);

  Uint8List? get data => _data;

  bool get isSuccess => _isSuccess;

  String get uuid => _uuid;

  DeviceSignalType get type => _type; //写入返回的数据

}


///标示设备返回数据的场景的枚举类
enum DeviceSignalType {
  ///特征值读
  characteristicsRead,

  ///特征值写
  characteristicsWrite,

  ///特征值通知
  characteristicsNotify,

  ///描述读
  descriptorRead,

  ///描述写
  descriptorWrite,

  ///无法判断,因为ios平台下characteristicsRead和characteristicsNotify是一样的
  unKnown
}

///返回发现的蓝牙服务
class BleService {
  ///服务UUID
  final String _serviceUuid;

  ///特征值信息
  final List<BleCharacteristic> _characteristics;

  BleService(this._serviceUuid, this._characteristics);

  List<BleCharacteristic> get characteristics => _characteristics;

  String get serviceUuid => _serviceUuid; //特征值UUID

}